package cn.axj.crypt.secret.implement;

import cn.axj.crypt.config.CryptProperties;
import cn.axj.crypt.constant.AlgorithmConstant;
import cn.axj.crypt.secret.BaseAlgorithmHttpInputMessage;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;

/**
 * @author aoxiaojun
 * @date 2021/1/27 17:09
 **/
@Component
public class Base64AlgorithmHttpInputMessage extends BaseAlgorithmHttpInputMessage {

    @Resource
    private CryptProperties cryptProperties;


    @Override
    public String getBinding() {
        return AlgorithmConstant.BASE64;
    }

    @Override
    public String decrypt(String content) throws Exception {
        return new String(decode(content),cryptProperties.getCharset());
    }

    @Override
    public String encrypt(String content) throws Exception {
        return encode(content.getBytes(cryptProperties.getCharset()));
    }


    private byte[] decode(String base64)  {
        return Base64.decodeBase64(base64);
    }


    private String encode(byte[] bytes)   {
        try {
            return new String(Base64.encodeBase64(bytes), cryptProperties.getCharset());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}
